package com.ruoyi.canteen.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.ruoyi.canteen.domain.CanteenCpOrderLog;
import com.ruoyi.canteen.domain.CanteenCpOrderReturn;
import com.ruoyi.canteen.domain.CanteenUser;
import com.ruoyi.canteen.service.*;
import com.ruoyi.canteen.utils.JwtToken;
import com.ruoyi.canteen.vo.CanteenOrderItemVo;
import com.ruoyi.canteen.vo.OrderAndItemListVo;
import com.ruoyi.canteen.vo.OrderShowVo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 退费接口
 * @Author Ryan
 * @Date 2022/4/7 16:40
 * @Version 1.0
 */
@RestController
@RequestMapping("/v1/orderReturn")
public class OrderReturnApiController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(OrderReturnApiController.class);

    @Autowired
    private ICanteenUserService canteenUserService;

    @Autowired
    private ICanteenCpOrderReturnService canteenCpOrderReturnService;

    @Autowired
    private ICanteenCpOrderDetailService canteenCpOrderDetailService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    @Autowired
    private ICanteenCpOrderLogService canteenCpOrderLogService;

    @Autowired
    private ICanteenCpOrderService canteenCpOrderService;

    /**
     * 根据登录用户查询所管理的门店退单
     * @param token
     * @return
     */
    @GetMapping("/listByUser/{token}")
    public AjaxResult listByUser(@PathVariable("token") String token)
    {
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            //1. 根据用户信息查auth_code,获取管理门店
            CanteenUser canteenUser = canteenUserService.selectCanteenUserById(uid.toString());
            String authCode = canteenUser.getAuthCode();
            if(StringUtils.isNotEmpty(authCode)){
                //2. 查询门店中所有退单(当天)：待审核、已退回、已审核
                String mdIds = "";
                if(authCode.contains("#")){
                    mdIds = authCode.replaceAll("#", ",");
                }else{
                    mdIds = authCode;
                }
                List<OrderShowVo> list =
                        canteenCpOrderReturnService.selectDefaultOrderShowVoList(mdIds);
                Map<Long, List<CanteenOrderItemVo>> orderItemMap = new HashMap<>();
                for (OrderShowVo curOrder : list) {
                    List<CanteenOrderItemVo> itemVos =
                            canteenCpOrderDetailService.selectOrderDetailListByOrderId(curOrder.getOrderId());
                    orderItemMap.put(curOrder.getOrderId(), itemVos);
                }
                return AjaxResult.success(new OrderAndItemListVo(list, orderItemMap));
            }else{
                return AjaxResult.success(null);
            }
        }else{
            return AjaxResult.error("登录信息失效，请先登录");
        }
    }

    /**
     * 获取发起退款原因
     * @return
     */
    @GetMapping("/getReturnReasons")
    public AjaxResult getReturnReasons(){
        List<SysDictData> reasonDict = dictTypeService.selectDictDataByType("return_reseaon");
        return AjaxResult.success(reasonDict);
    }

    /**
     * 驳回退款
     * @return
     */
    @PostMapping("/backReturn")
    public AjaxResult backReturn(@RequestBody JSONObject jsonObject){
        String orderId = jsonObject.getString("orderId");
        String token = jsonObject.getString("token");
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            //
            return canteenCpOrderReturnService.backReturn(orderId, uid.toString());
        }
        return AjaxResult.error("请重新登录");
    }

    /**
     * 微卡同意退款
     * @return
     */
    @PostMapping("/agreeReturn")
    public AjaxResult agreeReturn(@RequestBody JSONObject jsonObject){
        String orderId = jsonObject.getString("orderId");
        String token = jsonObject.getString("token");
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            // TODO 验证用户是否拥有对应权限
            CanteenUser user = canteenUserService.selectCanteenUserById(uid.toString());
            String authCode = user.getAuthCode();
            CanteenCpOrderReturn queryOrderReturn = new CanteenCpOrderReturn();
            queryOrderReturn.setOrderId(Long.valueOf(orderId));
            List<CanteenCpOrderReturn> orderReturns =
                    canteenCpOrderReturnService.selectCanteenCpOrderReturnList(queryOrderReturn);
            if(orderReturns.size() > 0){
                CanteenCpOrderReturn orderReturn = orderReturns.get(0);
                if(!orderReturn.getReturnApplyStatus().equals(1)){
                    return new AjaxResult(500,"无法再次审核");
                }
                if(authCode.contains(orderReturn.getMdId().toString())){
                    AjaxResult result = canteenCpOrderReturnService.agreeReturn(orderId, uid.toString());
                    return result;
                }
            }
            return AjaxResult.error("无权退款");
        }
        return AjaxResult.error("请重新登录");
    }

    /**
     * 微信-确认退款（退款成功，写入微信支付日志、订单及退单状态变更）
     * @param jsonParam 微信支付反馈json 参数值
     * @return
     */
    @PostMapping(value = "/confirmRefundByWx")
    public AjaxResult confirmRefundByWx(@RequestBody JSONObject jsonParam){
        String data = jsonParam.getString("data");
        JSONObject dataObj = jsonParam.getJSONObject("data");
        String openId = dataObj.getJSONObject("userInfo").get("openId").toString();
        CanteenUser queryUser = new CanteenUser();
        queryUser.setOpenid(openId);
        List<CanteenUser> userList =  canteenUserService.selectCanteenUserList(queryUser);
        logger.info(jsonParam.toJSONString());
        // 写入日志表
        CanteenCpOrderLog canteenCpOrderLog = new CanteenCpOrderLog();
        canteenCpOrderLog.setLogType(Long.valueOf(3));
        canteenCpOrderLog.setOrderNo(dataObj.getString("outTradeNo"));
        canteenCpOrderLog.setLogContent(data);
        canteenCpOrderLog.setOperator("wxRefundbak");
        canteenCpOrderLog.setLogTime(new Date());
        canteenCpOrderLogService.insertCanteenCpOrderLog(canteenCpOrderLog);
        if(!StringUtils.isEmpty(data)) {
            Long userId = userList.get(0).getId();
            String orderNo = dataObj.getString("outTradeNo");
            return canteenCpOrderReturnService.refundBySys(orderNo, userId, jsonParam);
//            return AjaxResult.success("退款成功");
        }else{
            log.error("授权失败：", jsonParam.toJSONString());
            return AjaxResult.error("失败,联系管理员");
        }
    }

    /**
     * 微信-验证退款信息
     * @param jsonParam 退款人、订单信息
     * @return
     */
    @PostMapping(value = "/checkRefundByWx")
    public AjaxResult checkRefundByWx(@RequestBody JSONObject jsonParam){
        String orderId = jsonParam.getString("orderId");
        String token = jsonParam.getString("token");
        Optional<Map<String, Claim>> optionalMap = JwtToken.getClaims(token);
        if(optionalMap.isPresent()) {
            Map<String, Claim> map = optionalMap.get();
            Long uid = map.get("uid").asLong();
            // TODO 验证用户是否拥有对应权限
            CanteenUser user = canteenUserService.selectCanteenUserById(uid.toString());
            String authCode = user.getAuthCode();
            CanteenCpOrderReturn queryOrderReturn = new CanteenCpOrderReturn();
            queryOrderReturn.setOrderId(Long.valueOf(orderId));
            List<CanteenCpOrderReturn> orderReturns =
                    canteenCpOrderReturnService.selectCanteenCpOrderReturnList(queryOrderReturn);
            if(orderReturns.size() > 0){
                CanteenCpOrderReturn orderReturn = orderReturns.get(0);
                if(authCode.contains(orderReturn.getMdId().toString())){
                    return AjaxResult.success("可以退款");
                }
            }
            return AjaxResult.error("无权退款");
        }
        return AjaxResult.error("请重新登录");
    }
}
